package com.xky.ui.module.productManagement.add;

import com.xky.utils.DBUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.*;

public class AddCategory extends JFrame {
    private JPanel jPanel1, jPanel2, jPanel3;
    private JTextField[] textFields;
    private JComboBox<String> isActiveComboBox;
    
    // 定义颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);

    public AddCategory() {
        setTitle("添加商品分类");
        setSize(500, 600);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        init();
        setVisible(true);
    }

    void init() {
        setLayout(new BorderLayout()); // 设置主布局
        
        // 创建主面板并设置背景渐变
        JPanel mainPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                int w = getWidth();
                int h = getHeight();
                GradientPaint gp = new GradientPaint(0, 0, SECONDARY_COLOR, 0, h, new Color(230, 240, 250));
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, w, h);
            }
        };
        mainPanel.setLayout(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        
        // 标题面板
        jPanel2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
        jPanel2.setOpaque(false);
        
        JLabel jLabel = new JLabel("添加商品分类信息");
        jLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        jLabel.setForeground(PRIMARY_COLOR);
        jPanel2.add(jLabel);
        
        // 添加分隔线
        JSeparator separator = new JSeparator();
        separator.setForeground(PRIMARY_COLOR);
        separator.setPreferredSize(new Dimension(450, 2));
        
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setOpaque(false);
        titlePanel.add(jPanel2, BorderLayout.CENTER);
        titlePanel.add(separator, BorderLayout.SOUTH);
        titlePanel.setBorder(new EmptyBorder(0, 0, 20, 0));
        
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 表单面板
        jPanel1 = new JPanel(new GridBagLayout());
        jPanel1.setOpaque(false);
        
        JLabel[] labels = new JLabel[]{
                new JLabel("分类ID *"),
                new JLabel("分类名称 *"),
                new JLabel("父分类ID *"),
                new JLabel("是否启用 *")
        };

        // 创建文本框数组
        textFields = new JTextField[3];

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 0;
        gbc.insets = new Insets(10, 10, 10, 10);

        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
        Font inputFont = new Font("微软雅黑", Font.PLAIN, 16);
        
        // 创建圆角边框的文本框样式
        for (int i = 0; i < labels.length; i++) {
            gbc.gridx = 0;
            gbc.gridy = i;
            gbc.anchor = GridBagConstraints.WEST;
            labels[i].setFont(labelFont);
            labels[i].setForeground(PRIMARY_COLOR);
            jPanel1.add(labels[i], gbc);
            
            gbc.gridx = 1;
            gbc.weightx = 1.0;
            
            if (i < 3) {
                // 前三个是文本框：分类ID、分类名称、父分类ID
                textFields[i] = new JTextField(20);
                textFields[i].setFont(inputFont);
                textFields[i].setPreferredSize(new Dimension(250, 35));
                jPanel1.add(textFields[i], gbc);
            } else {
                // 是否启用下拉框
                isActiveComboBox = new JComboBox<>(new String[]{"是", "否"});
                isActiveComboBox.setFont(inputFont);
                isActiveComboBox.setPreferredSize(new Dimension(250, 35));
                isActiveComboBox.setBackground(Color.WHITE);
                jPanel1.add(isActiveComboBox, gbc);
            }
        }

        
        // 添加表单面板到卡片容器
        JPanel formCard = createRoundedPanel();
        formCard.setLayout(new BorderLayout());
        formCard.add(jPanel1, BorderLayout.CENTER);
        formCard.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        mainPanel.add(formCard, BorderLayout.CENTER);

        // 按钮面板
        jPanel3 = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        jPanel3.setOpaque(false);
        
        JButton submitButton = new JButton("提交");
        submitButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        submitButton.setPreferredSize(new Dimension(120, 40));
        submitButton.setBackground(BUTTON_COLOR);
        submitButton.setForeground(Color.WHITE);
        submitButton.setFocusPainted(false);
        submitButton.setBorderPainted(false);
        
        JButton resetButton = new JButton("重置");
        resetButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        resetButton.setPreferredSize(new Dimension(120, 40));
        resetButton.setBackground(Color.LIGHT_GRAY);
        resetButton.setForeground(Color.WHITE);
        resetButton.setFocusPainted(false);
        resetButton.setBorderPainted(false);
        
        jPanel3.add(submitButton);
        jPanel3.add(resetButton);
        
        mainPanel.add(jPanel3, BorderLayout.SOUTH);
        add(mainPanel);

        // 重置按钮事件
        resetButton.addActionListener(_ -> {
            for (JTextField field : textFields) {
                field.setText("");
            }
            isActiveComboBox.setSelectedIndex(0);
        });

        // 提交按钮事件
        submitButton.addActionListener(e -> {
            try {
                // 获取输入值
                String categoryIdStr = textFields[0].getText().trim();
                String categoryName = textFields[1].getText().trim();
                String parentIdStr = textFields[2].getText().trim();
                String isActive = isActiveComboBox.getSelectedIndex() == 0 ? "1" : "0"; // "是"对应1，"否"对应0
                
                // 进行输入校验
                if (categoryIdStr.isEmpty() || categoryName.isEmpty() || parentIdStr.isEmpty()) {
                    showValidationError("所有字段都为必填项，请完成表单");
                    return;
                }
                
                try {
                    Integer categoryId = Integer.valueOf(categoryIdStr);
                    Integer parentId = Integer.valueOf(parentIdStr);
                    
                    // 进行输入校验
                    if (!validateInputs(categoryId, categoryName, parentId, isActive)) {
                        return; // 如果校验不通过，直接返回
                    }
                    
                    if (addCategory(categoryId, categoryName, parentId, isActive)) {
                        JOptionPane.showMessageDialog(AddCategory.this, "商品分类添加成功！", "成功提示", JOptionPane.INFORMATION_MESSAGE);
                        dispose();
                    } else {
                        JOptionPane.showMessageDialog(AddCategory.this, "商品分类添加失败！", "失败提示", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (NumberFormatException ex) {
                    showValidationError("分类ID和父分类ID必须是数字");
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(AddCategory.this, "发生错误：" + ex.getMessage(), "错误提示", JOptionPane.ERROR_MESSAGE);
            }
        });
    }
    
    /**
     * 创建带圆角和阴影的面板
     */
    private JPanel createRoundedPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(Color.WHITE);
                g2d.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
            }
        };
        panel.setOpaque(false);
        
        // 添加阴影边框
        panel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5),
            BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230), 1),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)
            )
        ));
        
        return panel;
    }

    /**
     * 校验用户输入的数据
     * @return 如果所有输入都有效返回true，否则返回false
     */
    private boolean validateInputs(Integer categoryId, String categoryName, Integer parentId, String isActive) {
        // 1. 校验分类ID
        if (categoryId <= 0) {
            showValidationError("分类ID必须大于0");
            return false;
        }

        // 2. 校验分类名称
        if (categoryName.isEmpty()) {
            showValidationError("商品分类名称不能为空");
            return false;
        }

        // 3. 校验父分类ID
        if (parentId < 0) {
            showValidationError("父分类ID不能小于0");
            return false;
        }
        
        // 所有校验通过
        return true;
    }

    /**
     * 显示验证错误信息
     * @param message 错误信息
     */
    private void showValidationError(String message) {
        JOptionPane.showMessageDialog(this, message, "输入错误", JOptionPane.WARNING_MESSAGE);
    }

    public boolean addCategory(Integer categoryId, String categoryName, Integer parentId, String isActive) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement(
                "INSERT INTO product_categories(category_id, category_name, parent_id, is_active, updated_time, created_time) VALUES (?, ?, ?, ?, NOW(), NOW())",
                Statement.RETURN_GENERATED_KEYS
            );
            preparedStatement.setInt(1, categoryId);
            preparedStatement.setString(2, categoryName);
            preparedStatement.setInt(3, parentId);
            preparedStatement.setString(4, isActive);

            int i = preparedStatement.executeUpdate();

            if (i > 0) {
                System.out.println("影响行数为" + i + "添加成功！");
                return true;
            } else {
                System.out.println("影响行数为" + i + "添加失败！");
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }

    public static void main(String[] args) {
        try {
            // 尝试使用系统外观
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        SwingUtilities.invokeLater(AddCategory::new);
    }
}